//
//  Download.m
//  Pico y placa
//
//  Created by DmpmMacPro on 1/02/13.
//  Copyright (c) 2013 Mario Franco. All rights reserved.
//

#import "Download.h"

@implementation Download
{
    NSMutableData * webData;
    
}

@synthesize url, nombre, pathDestino, downloader;


- (id)initWithDowloader: (FileDownloader * ) downlo
{
    self = [super init];
    if (self) {
        downloader = downlo;
        NSLog(@"Downloader: %@",downloader);
    }
    return self;
}

- (void) iniciarDescarga: (NSString *) urlPath nombreId: (NSString *) name pathDestino: (NSString *) destino
{
    if( urlPath)
    {
        url = [NSURL URLWithString:urlPath];
    }
    if(name)
    {
        nombre = name;
    }
    if(destino)
    {
       pathDestino = destino;
    }
    
   // NSLog(@"entro a descarga %@, %@, %@", url, nombre,pathDestino);
    NSMutableURLRequest * theRequest = [NSMutableURLRequest requestWithURL:url];
    NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self ];// startImmediately:YES];
    if(connection)
    {
        webData = [NSMutableData data];
        [connection start];
        NSLog(@"Iniciando descarga con conexion %@", connection.description);
    }
    else
    {
        NSLog(@"ERROR EN LA CONEXION!!!!");
    }
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"descartando datos..");
    [webData setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"Recibiendo datos..");
    [webData appendData:data];
    //write to filesystem instead of keeping data in memory
   // [data writeToURL:localFileURL options:0 error:nil];
}

- (void) connectionDidFinishLoading: (NSURLConnection *) connection
{
    

    NSURL *fileURL = [NSURL fileURLWithPath:pathDestino];
    NSError *writeError = nil;
    
    [webData writeToURL: fileURL options:0 error:&writeError];
    
    if( writeError) {
        NSLog(@" Error in writing file %@' : \n %@ ", pathDestino , writeError );
        return;
    }
    
    
    [downloader reportarTerminacionDescargarConIdentificador:nombre conData:webData];
    
    NSLog(@"Termino descarga de %@",nombre);
    
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error !" message:@"Error has occured, please verify internet connection.."  delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    
    NSLog(@"Fallo");
    [alert show];
    
}

@end
